<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span v-if="this.$route.params.id">编辑角色</span>
        <span v-else>添加角色</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="active">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="active === 1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="180px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="userForm.roleName" size="mini" style="width: 600px;" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="userForm.remark" size="mini" style="width: 600px;" type="textarea" placeholder="请输入角色描述" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="active === 2" class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div v-for="(item,index) in treeDatas" :key="item.id" class="tree-item">
              <div class="tree-title"> {{ item.title }} </div>
              <!-- 要检查树状数据是否是数组？ -->
              <!-- 如果有多个元素使用了相同的ref名称，则this.$refs会返回一个数组，包含所有这些元素 -->
              <el-tree
                ref="tree"
                :data="item.children"
                :props="defaultProps"
                :default-checked-keys="checkedKeys[index]"
                default-expand-all
                :expand-on-click-node="false"
                show-checkbox
                node-key="id"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="active === 3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <el-row>{{ '角色名称:'+userForm.name }}</el-row>
          <el-row>{{ '角色名称:'+userForm.description }}</el-row>
          <el-row>角色权限:</el-row>
          <div class="form">
            <div class="tree-wrapper">
              <div v-for="item in treeDatas2" :key="item.id" class="tree-item">
                <div class="tree-title"> {{ item.title }} </div>
                <el-tree
                  ref="tree2"
                  :data="item.children"
                  :props="defaultProps"
                  default-expand-all
                  :expand-on-click-node="false"
                  show-checkbox
                  node-key="id"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="active > 1" @click="active--">上一步</el-button>
        <el-button v-if="active < 3" type="primary" @click="next">下一步</el-button>
        <el-button v-if="active === 3" type="primary" @click="addRole">完成</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addRoleAPI, getRolePermisionAPI, getTreeDataAPI, updateRoleAPI } from '@/api/system'

export default {
  data() {
    return {
      active: 1, // 当前激活的步骤
      userForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      userFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      treeDatas: [], // 树状数据
      treeDatas2: [], // 树状数据2
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      checkedKeys: []

    }
  },
  created() {
    this.getTreeData()
    this.getRolePermision()
  },
  methods: {
    // 如果有id，则根据id获取角色权限
    async getRolePermision() {
      if (this.$route.params.id) {
        const res = await getRolePermisionAPI(this.$route.params.id)
        console.log(res)
        this.userForm.roleName = res.data.roleName
        this.userForm.remark = res.data.remark
        this.checkedKeys = res.data.perms
      }
    },
    async addRole() {
      if (this.$route.params.id) {
        await updateRoleAPI({ ...this.userForm, roleId: this.$route.params.id })
        this.$message.success('编辑成功')
      } else {
        await addRoleAPI(this.userForm)
        this.$message.success('添加成功')
      }
      this.$router.back()
    },
    // 点击下一步
    async next() {
      // 如果此时active为1，则校验角色表单
      if (this.active === 1) {
        await this.$refs.userFormRef.validate()
        // 校验通过再前往下一步
        this.active++
      } else if (this.active === 2) {
        // 获取选中的树状数据
        const treeList = this.$refs.tree
        treeList.forEach(item => {
          this.userForm.perms.push(item.getCheckedKeys())
        })
        // 判断是否至少选中了一项
        if (this.userForm.perms.flat().length === 0) {
          this.$message.error('请至少选择一项权限')
        } else {
          this.active++
          // 给树状数据设置禁用
          // 注意：如果组件是用v-if控制显示/隐藏，则此时找不到下一页的元素，需要使用v-show控制显示/隐藏
          this.$refs.tree2.forEach((item, index) => {
            item.setCheckedKeys(this.userForm.perms[index], false)
          })
        }
      }
    },
    // 设置禁用
    addDisabled(data) {
      data.forEach(item => {
        item.disabled = true
        if (item.children) {
          this.addDisabled(item.children)
        }
      })
    },
    // 获取树状权限数据
    async getTreeData() {
      const res = await getTreeDataAPI()
      this.treeDatas = res.data
      // 需要和treeData进行区分，不然会导致第一个树状数据被禁用
      // 深拷贝
      this.treeDatas2 = JSON.parse(JSON.stringify(res.data))
      // 给所有的树状数据添加禁用属性
      this.addDisabled(this.treeDatas2)
    }
  }

}
</script>

<style scoped lang="scss">
.add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        position: fixed;
        top: 64px;
        bottom: 88px;
        width: 100%;
        overflow-y: auto;
        background: #f4f6f8;
        padding: 20px 230px;
        display: flex;

        .step-container {
            height: 400px;
            width: 200px;
        }

        .form-container {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;
                }

                .info {
                    font-size: 14px;
                    color: #666;

                    .form-item {
                        margin-bottom: 20px;
                    }
                }
            }

            .form-box {
                width: 600px;
                display: flex;
                flex-direction: column;
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
        z-index: 10001;
    }

    .tree-wrapper {
        display: flex;
        flex-wrap: wrap;

        .tree-item {
            width: 33%;
            padding: 0px 4px;
            text-align: center;

            .tree-title {
                background: #f5f7fa;
                text-align: center;
                padding: 10px 0;
                margin-bottom: 12px;
            }
        }
    }
}
</style>
